<template>
  <div class="news-add-or-update">
    <el-drawer :title="this.rowData ? '编辑' : '新增'" :visible.sync="drawer" custom-class="demo-drawer" direction="rtl" :before-close="cancelForm" size="88%">
      <div class="demo-drawer__content">
        <div :style="cardHeightStyle" class="rightScrollNone">
          <el-form size="mini" :model="dataForm" :rules="rules" ref="vendorRuleForm">
            <el-row>
              <el-col :span="24">
                <el-form-item :label-width="formLabelWidth" label="任务名称：" prop="name">
                  <el-input autocomplete="off" type="text" v-model="dataForm.name"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item :label-width="formLabelWidth" label="脚本文件：" prop="path">
                  <el-upload :accept="'.py'" :before-remove="beforeRemove" :file-list="fileList" :http-request="UploadImage" :limit="1" :on-exceed="handleExceed" :on-preview="handlePreview" :on-remove="handleRemove" :on-success="Success" action="string" class="upload-demo" multiple>
                    <el-button size="mini" type="primary" :loading="uploading" v-if="uploading">上传中</el-button>
                    <el-button size="mini" type="primary" :loading="uploading" v-else>点击上传</el-button>
                  </el-upload>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item :label-width="formLabelWidth" label="优先级：" prop="sort">
                  <el-input auto-complete="off" type="number" v-model="dataForm.sort"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item :label-width="formLabelWidth" label="执行类型：" prop="label">
                  <el-select placeholder="请选择" style="width: 100%" v-model="dataForm.label">
                    <el-option :key="item.id" :label="item.name" :value="item.id" v-for="item in taskClass"> </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24" v-if="dataForm.label === '2'">
                <el-form-item :label-width="formLabelWidth" label="执行时间：" prop="run_time">
                  <el-date-picker v-model="dataForm.run_time" type="datetime" placeholder="选择执行时间" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
                </el-form-item>
              </el-col>

              <el-col :span="24" v-if="dataForm.label === '1'">
                <el-form-item :label-width="formLabelWidth" label="执行周期：" prop="cycle_label">
                  <el-select placeholder="请选择" style="width: 100%" v-model="dataForm.cycle_label">
                    <el-option :key="item.id" :label="item.name" :value="item.id" v-for="item in cycleArr"> </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="24" v-if="dataForm.cycle_label === '月'">
                <el-form-item :label-width="formLabelWidth" label="执行粒度：" prop="dataForm.month">
                  <el-select placeholder="请选择月份" style="width: 100%" v-model="dataForm.month">
                    <el-option :key="month" :label="month" :value="month" v-for="month in months"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="24" v-if="dataForm.cycle_label === '周'">
                <el-form-item :label-width="formLabelWidth" label="执行粒度：" prop="dataForm.week">
                  <el-select placeholder="请选择星期" style="width: 100%" v-model="dataForm.week">
                    <el-option :key="dayOfWeek" :label="dayOfWeek" :value="dayOfWeek" v-for="dayOfWeek in daysOfWeek"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="24" v-if="dataForm.cycle_label === '日'">
                <el-form-item :label-width="formLabelWidth" label="执行粒度：" prop="dataForm.day">
                  <el-select placeholder="请选择时间" style="width: 100%" v-model="dataForm.day">
                    <el-option :key="day" :label="day" :value="day" v-for="day in times"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item :label-width="formLabelWidth" label="任务描述：" prop="content">
                  <tinymce v-model="dataForm.content" :height="500" v-if="drawer_tinymce" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div class="demo-drawer__footer">
          <el-button size="mini" @click="cancelForm">取 消</el-button>
          <el-button size="mini" :loading="loading" @click="dataFormSubmit(1)" type="primary">确定</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import Tinymce from '@/components/Tinymce'
import { upfile } from '@/api/baseInfo'
import { AddTaskApi, EditTaskApi, TaskArrApi } from '@/api/project'
import { uploadScript } from '@/api/api'

export default {
  data() {
    return {
      dataForm: {
        id: '',
        name: '',
        path: '',
        sort: 1,
        run_time: '',
        content: '',
        label: '',
        cycle_label: '',
      },
      rowData: null,
      formLabelWidth: '180px',
      loading: false,
      drawer: false,
      drawer_tinymce: false,
      rules: {
        name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
      },
      dialogImageUrl: '',
      dialogVisible: false,
      taskClass: [
        { id: '1', name: '定时任务' },
        { id: '2', name: '实时任务' },
      ],
      cycleArr: [
        { id: '月', name: '月' },
        { id: '周', name: '周' },
        { id: '日', name: '日' },
      ],
      fileList: [],
      wenjianming: [],
      uploading: false,
    }
  },
  mounted() {
    // this.getTaskArr();
  },
  components: { Tinymce },
  computed: {
    cardHeightStyle() {
      let documentClientHeight = document.body.clientHeight
      const height = documentClientHeight - 80 - 80
      return {
        height: height + 'px',
        'overflow-y': 'scroll',
        'padding-right': '20px;',
      }
    },
    months() {
      return Array.from({ length: 12 }, (_, i) => (i + 1).toString())
    },
    daysOfWeek() {
      return ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    },
    days() {
      return Array.from({ length: 31 }, (_, i) => (i + 1).toString())
    },
    times() {
      return Array.from({ length: 23 }, (_, i) => (i + 1).toString())
    },
  },

  methods: {
    UploadImage(param) {
      let _this = this
      this.uploading = true
      const formData = new FormData()
      formData.append('file', param.file)
      formData.append('extra', param.file.uid)
      uploadScript(formData)
        .then((res) => {
          _this.wenjianming.push({
            extra: param.file.uid,
            url: res.result,
          })
          param.file.id = res.result
          param.file.fileName = res.name
          param.onSuccess() // 上传成功的图片会显示绿色的对勾
          // 但是我们上传成功了图片， fileList 里面的值却没有改变，还好有on-change指令可以使用
        })
        .catch((response) => {
          param.onError()
        })
    },
    handlePreview(file) {
      // console.log(file.url)
      // if ((file.name.toLowerCase()).indexOf('.py') > -1) { // 证明是pdf文件
      //   window.open(file.url || 'http://' + location.host + '/appfile/' + file.raw.fileName)
      // } else {
      //   if (file.url) {
      //     this.download(file.url, file.name)
      //   } else {
      //     this.download('http://' + 'location.host' + '/appfile/' + file.raw.fileName, file.name)
      //   }
      // }
    },
    handleRemove(file, fileList) {
      // this.filename = fileList;
      // this.filename.push(fileList);
      for (var i = 0; i < this.wenjianming.length; i++) {
        if (this.wenjianming[i].extra == file.uid) {
          this.wenjianming.splice(i, 1)
        }
      }
    },
    Success(response, file, fileList) {
      this.uploading = false
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    editorValChangHandle(content) {
      this.dataForm.content = content
    },
    reportAdd(params) {
      return AddTaskApi(params)
        .then((res) => {
          if (res.code === 200) {
            this.$message.success('保存成功')
          }
        })
        .catch((res) => {
          this.$message.error('保存失败')
        })
    },
    reportUpdate(params) {
      return EditTaskApi(params)
        .then((res) => {
          if (res.code === 200) {
            this.$message.success('保存成功')
          }
        })
        .catch((res) => {
          this.$message.error('保存失败')
        })
    },
    dataFormSubmit(v) {
      this.$refs.vendorRuleForm.validate((flag) => {
        if (flag) {
          if (this.wenjianming.length > 0) {
            this.dataForm.path = this.wenjianming[0].url
          }
          const data = this.dataForm
          var request = this.rowData ? this.reportUpdate(data) : this.reportAdd(data)
          request
            .then((d) => {
              this.cancelForm()
              this.$emit('refreshList')
            })
            .catch((d) => {
              this.cancelForm()
            })
        }
      })
    },
    cancelForm() {
      this.cleanInfo()
      this.loading = false
      this.drawer = false
      this.drawer_tinymce = false
    },
    open(row, role) {
      if (this.drawer) {
        return
      }
      this.rowData = row || null
      this.drawer = true
      this.drawer_tinymce = true
      this.openHook()
    },
    clearData() {
      this.$refs.vendorRuleForm.resetFields()
    },
    cleanInfo() {
      this.dataForm.content = ''
    },
    openHook() {
      this.$nextTick((a) => {
        this.clearData()
        // this.$refs.quillEdit.open(this.rowData);
        if (this.rowData) {
          // 修改
          for (let key in this.dataForm) {
            this.dataForm[key] = this.rowData[key]
          }
        } else {
          this.loading = false
        }
      })
    },
  },
}
</script>
<style lang="scss">
.news-add-or-update {
  .icon-m {
    font-size: 25px;
    margin-left: 10px;

    position: relative;
    top: 4px;
    color: #03a9f4;
    cursor: pointer;
  }

  .el-tag {
    position: relative;
    right: 5px;
    z-index: 1;
    height: 40px;
    line-height: 40px;
    border-radius: 0 5px 5px 0;
    padding-left: 15px;
  }

  .my-email {
    .el-input__inner {
      border-radius: 5px 0 0 5px;
    }
  }
}

/*

*/

.fileInput {
  padding-right: 0;
}
</style>
